<template>
  <div>
    <el-select
      v-model="selectWidget.options.defaultPost"
      popper-class="global-select-down"
      class="width240"
      size="small">
      <el-option
        v-for="type in postTypes"
        :key="type.value"
        :label="type.label"
        :value="type.value" />
    </el-select>
    <el-select
      v-if="selectWidget.options.defaultPost === 2"
      v-model="selectWidget.options.follower"
      collapse-tags
      clearable
      popper-class="global-select-down"
      class="width240 mt"
      size="small">
      <el-option
        v-for="follower in followerList"
        :key="follower.key"
        :label="follower.name"
        :value="follower.key" />
    </el-select>
  </div>
</template>
<script>
export default {
  name: 'PostSelectProps',
  model: {
    prop: 'selectWidget',
    event: 'changeData'
  },
  props: {
    selectWidget: {
      type: Object,
      default: () => ({})
    },
    widgetData: {
      type: Object,
      default: () => {
        return {
          list: [],
          config: {
            labelWidth: 100, labelPosition: 'right',
            keyToFormula: {} // 公式字段的映射表（被引用的字段: 引用它的公式字段）
          }
        };
      }
    }
  },
  data() {
    return {
      followerList: []
    };
  },
  computed: {
    postTypes() {
      return [
        { value: 0, label: '无' },
        { value: 1, label: '创建人职位' },
        { value: 2, label: '跟随人员选择字段' }
      ];
    }
  },
  watch: {
    'selectWidget.options.defaultPost': {
      handler(val) {
        if (val === 2) {
          const isSubTable = !!this.selectWidget.isSubTable;
          this.getAllUserField(isSubTable);
        } else {
          this.$set(this.selectWidget.options, 'follower', null);
        }
      },
      immediate: true
    }
  },
  methods: {
    // 获取所有人员选择组件
    getAllUserField(isSubTable = false) {
      const { list } = this.widgetData;
      if (isSubTable) {
        const targetSubTable = list.filter(item => item.key === this.selectWidget.linkFormKey);
        const curSubForm = targetSubTable[0] || {};
        if (Array.isArray(curSubForm.subform) && curSubForm.subform.length) {
          this.followerList = curSubForm.subform.filter(item => item.type === 'user');
        }
      } else {
        const allOutUserList = list.filter(item => item.type === 'user');
        const allGridField = list.filter(item => item.type === 'grid');
        const allGridUserList = [];
        allGridField.forEach(gridField => {
          gridField.columns.forEach(column => {
            column.list.forEach(item => {
              if (item.type === 'user') {
                allGridUserList.push(item);
              }
            });
          });
        });
        this.followerList = [...allOutUserList, ...allGridUserList];
      }
    }
  }
};
</script>

<style scoped lang="scss">
.mt {
  margin-top: 10px;
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
</style>
